import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:life_milestones/MS-Model/MS-milestone.dart';
import 'package:life_milestones/controller/MS-mile-stone-controller.dart';
import 'package:provider/provider.dart';
import 'package:svgaplayer_flutter/svgaplayer_flutter.dart';
import '../util/MS-audio-player-util.dart';
import 'package:audioplayers/audioplayers.dart';
class MileStonePage extends StatelessWidget {
  MileStonePage({super.key});
  final List<String> months = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Aug",
    "Sept",
    "Oct",
    "Nov",
    "Dec"
  ];
  @override
  Widget build(BuildContext context) {
    context.read<MSMileStoneController>().refreshMilestoneList();
    return Consumer<MSMileStoneController>(
      builder: (BuildContext context, MSMileStoneController controller,
          Widget? child) {
        return Scaffold(
            resizeToAvoidBottomInset: false,
            extendBodyBehindAppBar: true,
            extendBody: true,
            body: SingleChildScrollView(
              physics: const AlwaysScrollableScrollPhysics(),
              child: DecoratedBox(
                  decoration: const BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage("images/mile-stone-bg.png"),
                          fit: BoxFit.fitWidth,
                          alignment: Alignment.topCenter),
                      color: Color(0xFF9AE270)),
                  child: ConstrainedBox(
                    constraints: BoxConstraints(
                        minHeight: ScreenUtil().screenHeight,
                        minWidth: ScreenUtil().screenWidth),
                    child: Stack(fit: StackFit.loose, children: [
                      Positioned(
                        top: 186.w,
                        bottom: 125.w,
                        left: 97.w,
                        child: Image.asset(
                          "images/mile-stone-line.png",
                          width: 16.w,
                          fit: BoxFit.fill,
                        ),
                      ),
                      Positioned(
                        bottom: 125.w,
                        left: 83.w,
                        child: Image.asset(
                          "images/mile-stone-end.png",
                          width: 44.w,
                        ),
                      ),
                      Column(children: [
                        ...List<Widget>.generate(months.length, (index) {
                          List<MSMileStone> list =
                              controller.milestones[index] ?? [];
                          return Padding(
                            padding: EdgeInsets.only(
                                top: index == 0 ? 209.w : 15.w,
                                left: 25.w,
                                right: 24.w),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Padding(
                                  padding: EdgeInsets.only(top: 10.w),
                                  child: Container(
                                    width: 61.w,
                                    height: 24.w,
                                    decoration: const BoxDecoration(
                                        image: DecorationImage(
                                            image: AssetImage(
                                                "images/mile-stone-mark-bg.png"))),
                                    alignment: Alignment.center,
                                    child: Text(
                                      months[index],
                                      style: TextStyle(
                                          fontSize: 12.sp,
                                          height: 1.5,
                                          fontWeight: FontWeight.w600,
                                          color: Color(0xFF634401)),
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding: EdgeInsets.only(
                                      left: 11.w, top: 20.w, right: 25.w),
                                  child: Container(
                                    width: 11.w,
                                    height: 2.w,
                                    decoration: BoxDecoration(
                                        borderRadius:
                                            BorderRadius.circular(2.w),
                                        color: Color(0xFF406CD5)),
                                  ),
                                ),
                                Column(
                                  children: [
                                    ...List<Widget>.generate(list.length,
                                        (index) {
                                      MSMileStone e = list[index];
                                      if (e.type == Type.text) {
                                        return Padding(
                                          padding: EdgeInsets.only(
                                              top: index != 0 ? 10.w : 0.w),
                                          child: Container(
                                            width: 218.w,
                                            padding: EdgeInsets.only(
                                                top: 10.w,
                                                bottom: 10.w,
                                                left: 15.w,
                                                right: 5.w),
                                            decoration: BoxDecoration(
                                                border: Border.all(
                                                    color: Color(0xFF108151),
                                                    width: 1.w),
                                                borderRadius:
                                                    BorderRadius.circular(10.w),
                                                color: Colors.white),
                                            child: Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                              children: [
                                                Text(
                                                  e.text,
                                                  style: TextStyle(
                                                      fontSize: 12.sp,
                                                      height: 1.5,
                                                      fontWeight:
                                                          FontWeight.w600,
                                                      color: Color(0xFF065F39)),
                                                ),
                                                InkWell(
                                                  onTap: () {
                                                    controller
                                                        .deleteMileStone(e);
                                                  },
                                                  child: Image.asset(
                                                    "images/mile-stone-delete.png",
                                                    width: 25.w,
                                                    fit: BoxFit.fitWidth,
                                                  ),
                                                )
                                              ],
                                            ),
                                          ),
                                        );
                                      }
                                      if (e.type == Type.voice) {
                                        return Padding(
                                          padding: EdgeInsets.only(
                                              top: index != 0 ? 10.w : 0.w),
                                          child: MSPlayingView(item: e.voice!,onDelete: (){
                                            controller.deleteMileStone(e);
                                          },),
                                        );
                                      }
                                      return Padding(
                                        padding: EdgeInsets.only(
                                            top: index != 0 ? 10.w : 0.w),
                                        child: Container(
                                          width: 218.w,
                                          height: 72.w,
                                          padding: EdgeInsets.only(
                                              top: 10.w,
                                              bottom: 10.w,
                                              left: 15.w,
                                              right: 5.w),
                                          decoration: BoxDecoration(
                                              border: Border.all(
                                                  color:
                                                      const Color(0xFF108151),
                                                  width: 1.w),
                                              borderRadius:
                                                  BorderRadius.circular(10.w),
                                              color: Colors.white),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Expanded(
                                                  child: ListView.builder(
                                                padding:
                                                    EdgeInsets.only(right: 5.w),
                                                itemBuilder:
                                                    (BuildContext context,
                                                        int index) {
                                                  return Padding(
                                                    padding: EdgeInsets.only(
                                                        left: index == 0
                                                            ? 0
                                                            : 5.w),
                                                    child: Container(
                                                        decoration:
                                                            BoxDecoration(
                                                          borderRadius:
                                                              BorderRadius
                                                                  .circular(
                                                                      10.w),
                                                        ),
                                                        clipBehavior:
                                                            Clip.antiAlias,
                                                        child: Image.file(
                                                          File(e.images[index]),
                                                          width: 52.w,
                                                          height: 52.w,
                                                          fit: BoxFit.cover,
                                                        )),
                                                  );
                                                },
                                                itemCount: e.images.length,
                                                scrollDirection:
                                                    Axis.horizontal,
                                              )),
                                              InkWell(
                                                onTap: () {
                                                  controller.deleteMileStone(e);
                                                },
                                                child: Image.asset(
                                                  "images/mile-stone-delete.png",
                                                  width: 25.w,
                                                  fit: BoxFit.fitWidth,
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                      );
                                    }),
                                    Padding(
                                      padding: EdgeInsets.only(
                                          top: list.isNotEmpty ? 10.w : 0.w),
                                      child: InkWell(
                                        onTap: () {
                                          Navigator.of(context).pushNamed(
                                              "/post",
                                              arguments: index);
                                        },
                                        child: Container(
                                          width: 218.w,
                                          padding: EdgeInsets.only(
                                              top: 10.w,
                                              bottom: 10.w,
                                              left: 15.w,
                                              right: 5.w),
                                          decoration: BoxDecoration(
                                              border: Border.all(
                                                  color:
                                                      const Color(0xFF108151),
                                                  width: 1.w),
                                              borderRadius:
                                                  BorderRadius.circular(10.w),
                                              color: Colors.white),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Text(
                                                "Leave what you want to say",
                                                style: TextStyle(
                                                    fontSize: 12.sp,
                                                    fontWeight: FontWeight.w600,
                                                    color: const Color(
                                                        0xFF999999)),
                                              ),
                                              InkWell(
                                                child: Image.asset(
                                                  "images/mile-stone-add.png",
                                                  width: 25.w,
                                                  fit: BoxFit.fitWidth,
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                )
                              ],
                            ),
                          );
                        }).toList(),
                        Container(
                          height: 250.w,
                        )
                      ])
                    ]),
                  )),
            ));
      },
    );
  }
}


class MSPlayingView extends StatefulWidget{
  final MSVoice item;
  final Function onDelete;
  const MSPlayingView({super.key, required this.item,required this.onDelete});
  @override
  State<StatefulWidget> createState() {
    return _MSPlayingViewState();
  }

}

class _MSPlayingViewState extends State<MSPlayingView> with SingleTickerProviderStateMixin{
  late SVGAAnimationController animationController;
  bool isPlaying = false;

  listener(PlayerState state){
    if(state == PlayerState.playing){
      setState(() {
        isPlaying = true;
      });
    }else{
      setState(() {
        isPlaying = false;
      });
    }
  }

  @override
  void initState() {
    animationController = SVGAAnimationController(vsync: this);
    loadAnimation();
    MSAudioPlayerUtil().addListener(key:widget.item.path,callBack: listener,);
    super.initState();
  }
  @override
  void dispose() {
    MSAudioPlayerUtil().removeListener(widget.item.path,listener);
    animationController.dispose();
    MSAudioPlayerUtil().stop();
    super.dispose();
  }
  void loadAnimation() async {
    final videoItem = await SVGAParser.shared.decodeFromAssets(
        "images/playing.svga");
    animationController.videoItem = videoItem;
    animationController.reset();
  }
  @override
  Widget build(BuildContext context) {

    return InkWell(
      onTap: () async {
        if(!isPlaying){
          setState(() {
            isPlaying = true;
          });
          await MSAudioPlayerUtil()
              .play(widget.item.path);
        }else{
          setState(() {
            isPlaying = false;
          });
          await MSAudioPlayerUtil().stop();
        }

      },
      child: Container(
        width: 218.w,
        padding: EdgeInsets.only(
            top: 10.w,
            bottom: 10.w,
            left: 15.w,
            right: 5.w),
        decoration: BoxDecoration(
            border: Border.all(
                color: Color(0xFF108151),
                width: 1.w),
            borderRadius:
            BorderRadius.circular(
                10.w),
            color: Colors.white),
        child: Row(
          mainAxisAlignment:
          MainAxisAlignment
              .spaceBetween,
          children: [
            Container(
              width: 98.w,
              height: 20.w,
              decoration: BoxDecoration(
                  borderRadius:
                  BorderRadius
                      .circular(10.w),
                  color:
                  const Color(0xFF70C37A)),
              padding: EdgeInsets.only(
                  left: 10.w),
              child: Row(
                children: [
                  if(isPlaying) SizedBox(width: 20.w, height: 20.w, child: const SVGASimpleImage(assetsName:"images/playing.svga",),),
                  if(!isPlaying) Container(width: 20.w, height: 20.w,alignment: Alignment.center, child: UnconstrainedBox(
                    child: Image.asset("images/mile-stone-voice.png",width: 14.w,fit: BoxFit.fitWidth,),
                  ),),
                  Padding(
                    padding:
                    EdgeInsets.only(
                        left: 4.w),
                    child: Text(
                      "${widget.item.length}S",
                      style: TextStyle(
                          fontSize: 12.sp,
                          color: const Color(
                              0xFF333333)),
                    ),
                  )
                ],
              ),
            ),
            InkWell(
              onTap: () {
               widget.onDelete();
              },
              child: Image.asset(
                "images/mile-stone-delete.png",
                width: 25.w,
                fit: BoxFit.fitWidth,
              ),
            )
          ],
        ),
      ),
    );
  }

}